<?php

namespace Frieza\Modules\Circle\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\Circle\WhiteList;
use Doraemon\cache\Queue;
use Doraemon\model\AdmUserType;
use Doraemon\model\Circle\CircleBaseInfo;
use Doraemon\model\Circle\CircleBaseInfo as mCircleBaseInfo;
use Doraemon\model\Circle\JoinCircle as mJoinCircle;
use Doraemon\model\Circle\PhotosCircle as mPhotosCircle;
use Doraemon\model\Es\Photo;
use Doraemon\model\Es\User;
use Doraemon\model\Member;
use Doraemon\service\Circle\Circle as sCircle;
use Doraemon\service\Circle\CircleBlack;
use Doraemon\service\Circle\CircleCommittee;
use Doraemon\model\Circle\CircleCommittee as mCircleCommittee;
use Doraemon\service\Circle\JoinCircle as sJoinCircle;
use Doraemon\service\Circle\PhotosCircle;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class CircleUserController extends Controller
{

    const YES = 1;
    const NO = 2;
    const ALL = 3;

    const FILTER_MAP = [
        self::YES => '是',
        self::NO => '否',
        self::ALL => '全部'
    ];

    public function checkUser(Request $request, Content $content, $circleId)
    {
        $pageSize = $request->input('per_page', 20);
        $page = $request->input('page', 1);
        $options = [
            'perPage' => $pageSize
        ];
        $params = $request->input();
        if ($params['uid']) {
            $where = [
                'uid' => $params['uid'],
                'circle_id' => $circleId,
                'join_status' => mJoinCircle::STATUS_NORMAL
            ];
            $count = mJoinCircle::count($where);
        } else {
            $uidList = $this->search($params, $circleId);
            $where = [
                'uid' => $uidList,
                'circle_id' => $circleId,
                'join_status' => mJoinCircle::STATUS_NORMAL
            ];
            $count = mJoinCircle::count($where);
            $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
            $where['ORDER'] = ['addtime' => 'DESC'];
        }
        $userInfos = mJoinCircle::selectByWhere($where) ?: [];
        //填充数据阶段
        $userInfos = array_column($userInfos, null, 'uid');
        $uids = array_column($userInfos, 'uid');
        $memberInfos = Member::getUserInfoByIds($uids) ?: [];
        $memberInfos = array_column($memberInfos, null, 'uid');
        $committeeInfos = CircleCommittee::getIsCommitteeByids($circleId, $uids);
        $circleHiddenCountList = PhotosCircle::getCircleHiddenCountByUidList($circleId, $uids);
        foreach ($userInfos as $uid => $userInfo) {
            $userInfos[$uid]['nick'] = $memberInfos[$uid]['nick'];
            $userInfos[$uid]['committee'] = $committeeInfos[$uid];
            $userInfos[$uid]['hidden_count'] = $circleHiddenCountList[$uid] ?: 0;
        }

        $gridModel = new pGridDataModel($userInfos, $count, $options);
        $listGird = Admin::grid($gridModel, function (Grid $grid) use ($circleId) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->dropDown('search_type', [
                        'uid' => 'uid',
                        'nick' => '用户昵称'
                    ]);
                });
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('is_committee', '是否圈委')->radio(self::FILTER_MAP)->default(self::ALL);
                });
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('show_status', '内容被折叠')->checkbox([self::YES => '是']);
                });
                $filter->expand();
            });

            $grid->quickCreate(function (Grid\Tools\QuickCreate $quickCreate) {
                $quickCreate->text('uid', '请输入uid');
            });
            $grid->column('uid', 'uid');
            $grid->column('nick', '用户昵称');
            $grid->column('addtime', '加入时间')->display(function () {
                return date('Y-m-d H:i:s', $this->addtime);
            });
            $grid->column('hidden_count', '用户被折叠数量')->display(function () {
                return $this->hidden_count == 0 ? '' : $this->hidden_count;
            });
            $grid->actions(function ($action) use ($circleId) {
                // 去掉编辑
                $action->disableEdit();
                // 去掉查看
                $action->disableView();
                //设置||移除圈委
                if ($action->row->committee) {
                    $action->append('<a href="/admin/circle/delCommittee/' . $circleId . '/' . $action->row->uid . ' " class="fa fa-user-times">取消圈委</a>');
                } else {
                    $action->append('<a href="/admin/circle/addCommittee/' . $circleId . '/' . $action->row->uid . ' " class="fa fa-user-plus">设为圈委</a>');
                }
            });
        });
        return $content->header('住友圈用户管理')->body($listGird)->breadcrumb(['text' => '圈子管理', 'url' => 'circle'], ['text' => '住友圈用户管理']);
    }

    public function deleteUser($circleId, $id)
    {
        try {
            if (empty($id)) {
                throw new \Exception('删除失败');
            }
            $uid = mJoinCircle::get('uid', ['id' => $id]);
            $joinInfo = mJoinCircle::getJoinInfo($circleId, $uid);
            if (!$joinInfo) {
                throw new \Exception('该用户已退出圈子');
            }
            $result = sJoinCircle::modifyUserCircleData($uid, $circleId, mJoinCircle::JOIN_CHANNEL_ADMIN, mJoinCircle::STATUS_DELETE, Admin::user()->id);
            if ($result) {
                $nick = Member::getNickByUid($uid);
                $circleName = CircleBaseInfo::getInfo(['circle_id' => $circleId], 'circle_name');
                // 删除圈子用户，折叠其全部圈子内容
                PhotosCircle::batchUpdatePhotoCircleByUid($uid, ['show_status' => mPhotosCircle::SHOW_STATUS_HIDDEN], mPhotosCircle::JOIN_CHANNEL_ADMIN, Admin::user()->id);
                Queue::insertQueue('queue/Sysmsg/Send', [
                    'msgCode' => 711,
                    'to_uid' => $uid,
                    'msgParams' => [
                        'nickName' => $nick,
                        'circleName' => $circleName
                    ]
                ], Queue::QUEUE_DORAEMON);
                //如果该用户是圈委 退出踢出圈子的同时移除圈委的身份
                if (CircleCommittee::wasCommittee($circleId, $uid)) {
                    sJoinCircle::exitCircleDelCommittee($circleId, $uid, Admin::user()->id);
                }
                //增加被踢出的计数器
                CircleBlack::removeCircle($uid);
            }
            return response()->json(
                [
                    'status' => true,
                    'message' => '删除成功'
                ]);
        } catch (\Exception $e) {
            admin_toastr($e->getMessage(), 'error');
        }
    }

    public function addUser(Request $request, $circleId)
    {
        try {
            $uid = $request->input('uid');
            $joinInfo = mJoinCircle::getJoinInfo($circleId, $uid);
            if ($joinInfo) {
                throw new \Exception('该用户已加入圈子');
            }

            $userInfo =  \Doraemon\service\User::getUserBaseInfo($uid);
            if (!$userInfo) {
                throw new \Exception('用户信息错误，请检查 uid 是否正确');
            }
            $userType = $userInfo['type'] ?? 0;
            $circle = mCircleBaseInfo::get('*', ['circle_id' => $circleId]);
            $whiteList = empty($circle['white_uid_list']) ? [] : json_decode($circle['white_uid_list'], true);
            $checkWhite = in_array($uid, $whiteList);
            $openCircle = sCircle::IS_WHITELIST_NO;

            if (in_array($userType, [Member::USER_COMMON, Member::AUTH_USER_V, Member::AUTH_ORG_V]) || $checkWhite) {
                $openCircle = sCircle::IS_WHITELIST_YES;
            }

            if (!$openCircle) {
                throw new \Exception('检查当前 uid 是否可以加入「该圈子」');
            }

            $userLevel = AdmUserType::getById($uid)['quality'];
            if ($userLevel == AdmUserType::B1 || $userLevel == AdmUserType::B2 || $userLevel == AdmUserType::B3) {
                throw new \Exception('该用户为B级用户');
            }
            $isExist = mJoinCircle::selectByWhere([
                'circle_id' => $circleId,
                'uid' => $uid,
                'join_status' => mJoinCircle::STATUS_NORMAL
            ]);
            if ($isExist) {
                throw new \Exception('请勿重复创建');
            }
            $result = sJoinCircle::modifyUserCircleData($uid, $circleId, mJoinCircle::JOIN_CHANNEL_ADMIN, mJoinCircle::STATUS_NORMAL, Admin::user()->id);
            if ($result) {
                $nick = Member::getNickByUid($uid);
                $circleName = CircleBaseInfo::getInfo(['circle_id' => $circleId], 'circle_name');
                Queue::insertQueue('queue/Sysmsg/Send', [
                    'msgCode' => 710,
                    'to_uid' => $uid,
                    'msgParams' => [
                        'nickName' => $nick,
                        'circleName' => $circleName
                    ]
                ], Queue::QUEUE_DORAEMON);
                return response()->json([
                    'status' => true,
                    'message' => "创建成功",
                ]);
            }
            return response()->json([
                'status' => true,
                'message' => "操作失败",
            ]);
        } catch (\Exception $exception) {
            $msg = $exception->getMessage();
            return response()->json([
                'status' => true,
                'message' => $msg,
            ]);
        }
    }

    public function addCommittee($circleId, $uid)
    {
        try {
            if (empty($circleId) || empty($uid)) {
                throw new \Exception('参数异常,操作失败');
            }
            $result = CircleCommittee::insertCommittee($circleId, $uid, mCircleCommittee::COMMITTEE_CHANNEL_ADMIN, Admin::user()->id);
            if ($result) {
                $success = new MessageBag([
                    'title' => '设置圈委成功'
                ]);
                return back()->with(compact('success'));
            }
            throw new \Exception('设置圈委失败，请重试');
        } catch (\Exception $exception) {
            $error = new MessageBag([
                'title' => $exception->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function delCommittee($circleId, $uid)
    {
        try {
            if (empty($circleId) || empty($uid)) {
                throw new \Exception('参数异常,请重试');
            }
            $isCommittee = CircleCommittee::wasCommittee($circleId, $uid);
            if (empty($isCommittee)) {
                throw new \Exception('该用户已经移除圈委身份');
            }
            $result = CircleCommittee::delCommittee($circleId, $uid, mCircleCommittee::COMMITTEE_CHANNEL_ADMIN, Admin::user()->id);
            if ($result) {
                $success = new MessageBag([
                    'title' => '移除圈委成功'
                ]);
                return back()->with(compact('success'));
            }
            throw new \Exception('移除圈委失败,请重试');
        } catch (\Exception $exception) {
            $error = new MessageBag([
                'title' => $exception->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    private function search($params, $circleId)
    {
        //默认情况把圈子所有用户查出来
        $joinWhere = [
            'join_status' => mJoinCircle::STATUS_NORMAL,
            'circle_id' => $circleId
        ];
        //三种情况 搜圈委 搜不是圈委 默认
        //如果搜索圈委先从圈委表取uidList
        if (isset($params['is_committee'])) {
            $committeeWhere = [
                'circle_id' => $circleId,
                'committee_status' => mCircleCommittee::STATUS_NORMAL,
            ];
            $committeeUidList = mCircleCommittee::selectByWhere($committeeWhere, 'uid');
            if ($params['is_committee'] == self::NO) {
                //搜索不是圈委先查圈委的id 再去joinUser[!]反查 获取到不是圈委的id
                if (!empty($committeeUidList)) {
                    $joinWhere['uid[!]'] = $committeeUidList;
                }
            } elseif ($params['is_committee'] == self::YES) {
                $joinWhere['uid'] = $committeeUidList;
            }
        }
        $uidList = mJoinCircle::selectByWhere($joinWhere, 'uid');
        if (isset($params['nick']) || isset($params['show_status'])) {
            return $this->buildEsWhereAndReturnUidList($params, $circleId, $uidList);
        }
        return $uidList;
    }

    //nick和折叠丢到es里查询
    private function buildEsWhereAndReturnUidList($params, $circleId, $uidList)
    {
        if ($params['nick']) {
            $nickWhere = [
                'nick_eng' => $params['nick'],
                'id' => $uidList
            ];
            $uidInfos = User::select('id', $nickWhere);
            $uidList = array_column($uidInfos['rows'], 'id');
            if (empty($uidList)) {
                return [];
            }
            if (empty($params['show_status'])) {
                return $uidList;
            }
        }
        $esWhere = [
            'circle_id' => $circleId,
            'uid' => $uidList,
            'circle_show_status' => mPhotosCircle::SHOW_STATUS_HIDDEN
        ];
        $uidInfos = Photo::getNoteListByParams($esWhere, 'uid');
        return array_column($uidInfos['rows'], 'uid');
    }

}